import type { ShareConfig } from './wxshare'
import cache from './cache'

export const ua = window.navigator.userAgent
export const userAgent = ua.toLowerCase()
export function isWxEnv(): boolean {
  return /MicroMessenger/i.test(userAgent) && !/wxwork/i.test(userAgent)
}

export const isAndroid = ua.includes('Android') || userAgent.includes('Linux')
export const isIos = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
export function isPobo() {
  if (isAndroid)
    return !!(window as any).pbESYS
  else if (isIos)
    return !!(((window as any).poboIOSApp || ((window as any).webkit && (window as any).webkit.messageHandlers && (window as any).webkit.messageHandlers.poboIOSApp)))

  return false
}
export const isETong = () => userAgent.includes('lightos/web')
export function isPlf() {
  if (isAndroid) {
    return Boolean(window.panAndroid)
  }
  else if (isIos) {
    if (window.webkit)
      return Boolean(window.webkit.messageHandlers)
  }
  return false
}

const staticchars = 'PXhw7UT1B0a9kQDKZsjIASmOezxYG4CHo5Jyfg2b8FLpEvRr3WtVnlqMidu6cN'
export function encode(_str: string, isZH?: boolean) { // 加密函数
  _str = encodeURI(_str)

  let encodechars = ''
  for (const i of _str) {
    const num0 = staticchars.indexOf(i)
    let code = i
    if (num0 !== -1)
      code = staticchars[(num0 + 3) % 62]

    const num1 = Number.parseInt(`${Math.random() * 62}`, 10)
    const num2 = Number.parseInt(`${Math.random() * 62}`, 10)
    encodechars += staticchars[num1] + code + staticchars[num2]
  }
  if (isZH)
    encodechars = encodechars.replace(/%/ig, '$')

  return encodechars
}

/**
 * 判断元素类型
 */
export function is(ele: any) {
  const type = Object.prototype.toString.call(ele)
  return type.match(/^\[object\s([A-Za-z]+)\]$/)![1].toLowerCase()
}

/* 判断是否是数组 */
export function isArray(data: any) {
  return is(data) === 'array'
}

/**
 * 数据是否为空
 * undefined、null、0、''、 {}、[] 判断为空
 */
export function isEmpty(data: any): boolean {
  switch (is(data)) {
    case 'undefined':
    case 'null':
    case 'string':
    case 'number':
      return !data
    case 'object':
      return !Object.keys(data).length
    case 'array':
      return !data.length
    case 'map':
    case 'set':
      return !data.size
  }
  return true
}

export function PBShare(config: ShareConfig) {
  const { title, desc, link } = config
  window.location.href
  = `pobo:pageId=800012&type=0&title=${
   encodeURIComponent(title)
   }&des=${
   encodeURIComponent(desc)
   }&url=${
   encodeURIComponent(link)}`
}

export function getImageUrl(name: string, ext = 'png') {
  return new URL(`../assets/images/${name}.${ext}`, import.meta.url).href
}

export function connectUrl(data: any): string {
  let url = ''
  for (const k in data) {
    const value = data[k] !== undefined ? data[k] : ''
    url += `&${k}=${encodeURIComponent(value)}` // 使用的es6的模板字符串的用法 ${}
  }
  return url ? url.substring(1) : '' // 这里主要判断data是否为空
}

export function getSecret(): string {
  let secret = cache.get('wxsceret_hatzjh')
  if (!secret) {
    secret = `${new Date().getTime()}_${(Math.random() * 10 ** (6)).toFixed(0)}`
    cache.set('wxsceret_hatzjh', secret)
  }
  return secret
}

export function setDuplicateLetters(arr: string, str: string): string {
  // 将字符串转换为字符数组
  let charArray: string[] = arr.split(',')

  if (charArray.includes(str)) {
    // 使用 filter 方法过滤出不重复的字符
    charArray = charArray.filter((char) => {
      return char !== str
    })
  }
  else {
    charArray.push(str)
  }
  // 将过滤后的字符数组转换为字符串
  const result: string = charArray.join(',')
  const regex: RegExp = /^,|,$/g
  return result.replace(regex, '')
}
